package com.xiaotao.learn.thread.file;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class WriteCompete {
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                byte[] content = (Thread.currentThread().getName() + " ").getBytes();
                FileOutputStream os;
                FileLock lock = null;
                try {
                    os = new FileOutputStream("a");
                    FileChannel channel = os.getChannel();
                    lock = channel.lock();
                    for (int j = 0; j < 10000; j++) {
                        os.write(content);
                    }
                    os.close();
                } catch (FileNotFoundException | OverlappingFileLockException e) {
                    System.out.println(Thread.currentThread().getName() + "无法获取到锁");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        new Thread(() -> {
            try {
                Files.delete(Paths.get("a"));
                System.out.println("===============================文件删除");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
